import '../prompt/prompt.css'
import Prompt from '../prompt/prompt.js'
import BasePlot from './basePlot';
import util from "../util";
/**
 * 文字标绘类
 * @class
 * @augments BasePlot
 * @alias BasePlot.CreateLabel
 */
class CreateLabel extends BasePlot {
  constructor(viewer, style) {
    super(viewer, style);
    this.type = "label";
    this.viewer = viewer;
    // this.style = style;
    /**
     * @property {Cesium.Cartesian3} 坐标
     */
    this.position = null;
    this.positionPoint = null;
    // 添加提示样式设置
    this.promptStyle = style.promptStyle || {};
    this.promptStyle.show = this.promptStyle.show !== undefined ? this.promptStyle.show : true;
  }


  start(callback) {
    // 初始化提示框
    if (!this.prompt && this.promptStyle.show) {
      this.prompt = new Prompt(this.viewer, this.promptStyle);
    }
    this.state = "startCreate";

    let that = this;
    if (!this.handler) {
      this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    }

    // 左键单击事件 - 创建标签
    this.handler.setInputAction(function (evt) {
      let cartesian = that.getCatesian3FromPX(evt.position, that.viewer);
      if (!cartesian) return;
      that.entity = that.createLabel(cartesian.clone());
      that.position = cartesian.clone();
      that.setStyle(that.style);
      that.endCreate();
      if (callback) callback(that.entity);
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 鼠标移动事件 - 更新提示信息
    this.handler.setInputAction(function (evt) {
      if (that.state === "startCreate") {
        // 初始状态提示
        that.prompt.update(evt.endPosition, "单击开始绘制文字");
      } else if (that.state === "creating") {
        // 创建过程中提示
        that.prompt.update(evt.endPosition, "单击确定文字位置");
      }
      that.state = "creating";
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  }


  /**
     * 创建位置定位点
     * @private
     */
  _createPositionIndicator() {
    // 移除已存在的标识点
    if (this.positionPoint) {
      this.viewer.entities.remove(this.positionPoint);
    }
    // 创建黄色带黑色边框的定位点
    this.positionPoint = this.viewer.entities.add({
      position: this.position,
      point: {
        pixelSize: 10,
        color: Cesium.Color.YELLOW,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        disableDepthTestDistance: Number.MAX_VALUE
      }
    });
    this.positionPoint.objId = this.objId;
  }

  endCreate() {
    let that = this;
    if (that.handler) {
      that.handler.destroy();
      that.handler = null;
    }
    // 销毁提示框
    if (that.prompt) {
      that.prompt.destroy();
      that.prompt = null;
    }
    that.state = "endCreate";
  }

  /**
   * 当前步骤结束
   */
  done() {
    if (this.state == "startCreate") {
      this.destroy();
    } else if (this.state == "creating") {
      this.destroy();
    } else if (this.state == "startEdit" || this.state == "editing") {
      this.endEdit();
    } else {

    }
  }

  createByPositions(lnglatArr, callback) {
    if (!lnglatArr) return;
    this.state = "startCreate";
    let position =
      lnglatArr instanceof Cesium.Cartesian3
        ? lnglatArr
        : Cesium.Cartesian3.fromDegrees(
          lnglatArr[0],
          lnglatArr[1],
          lnglatArr[2]
        );
    this.position = position;
    if (!position) return;
    this.entity = this.createLabel(position, this.style.text);
    if (callback) callback(this.entity);
    this.state = "endCreate";
  }

  // 设置相关样式
  setStyle(style) {
    if (!style || !this.entity) return;

    // 重置所有可能影响显示的样式属性
    this.entity.label.show = true;

    // 处理文字颜色
    if (style.fillColor) {
      let fillColor = Cesium.Color.fromCssColorString(style.fillColor || '#ffff00')
        .withAlpha(Number(style.fillColorAlpha) || 1);
      this.entity.label.fillColor = fillColor;
    }

    // 处理背景样式
    this.entity.label.showBackground = style.showBackground !== undefined ? style.showBackground : true;
    if (style.backgroundColor) {
      let backgroundColor = Cesium.Color.fromCssColorString(style.backgroundColor || '#000000')
        .withAlpha(Number(style.backgroundColorAlpha) || 1);
      this.entity.label.backgroundColor = backgroundColor;
    }

    // 处理其他样式
    this.entity.label.scale = Number(style.scale) || 1;
    this.entity.label.text = style.text || '';
    this.entity.label.heightReference = Number(style.heightReference) || 0;

    // 确保没有残留的偏移导致显示错位
    // 增强pixelOffset处理逻辑
    if (style.pixelOffset) {
      this.entity.label.pixelOffset = new Cesium.Cartesian2(Number(style.pixelOffset.x), Number(style.pixelOffset.y));
      console.log('this.entity.label.pixelOffset', this.entity.label.pixelOffset, style.pixelOffset)
    } else {
      this.entity.label.pixelOffset = Cesium.Cartesian2.ZERO;
    }

    this.style = Object.assign(this.style, style);
  }
  // 获取相关样式
  getStyle() {
    let obj = {};
    let label = this.entity.label;

    let fillColor = label.fillColor.getValue();
    obj.fillColorAlpha = fillColor.alpha;
    obj.fillColor = new Cesium.Color(
      fillColor.red,
      fillColor.green,
      fillColor.blue,
      1
    ).toCssHexString();

    if (label.outlineWidth != undefined) obj.outlineWidth = label.outlineWidth._value;
    if (label.showBackground != undefined) obj.showBackground = Boolean(label.showBackground.getValue());
    if (label.backgroundColor) {
      let bkColor = label.backgroundColor.getValue();
      obj.backgroundColorAlpha = bkColor.alpha;
      obj.backgroundColor = new Cesium.Color(bkColor.red, bkColor.green, bkColor.blue, 1).toCssHexString();
    }


    if (label.outlineColor) {
      let outlineColor = label.outlineColor.getValue();
      obj.outlineColorAlpha = outlineColor.alpha;
      obj.outlineColor = new Cesium.Color(outlineColor.red, outlineColor.green, outlineColor.blue, 1).toCssHexString();
    }

    if (label.heightReference != undefined) {
      obj.heightReference = label.heightReference.getValue();
    }

    if (label.pixelOffset) obj.pixelOffset = label.pixelOffset.getValue();

    if (label.scale) obj.scale = label.scale.getValue();

    obj.text = label.text.getValue();


    return obj;
  }
  getPositions(isWgs84) {
    return isWgs84 ? util.cartesianToLnglat(this.position) : this.position;
  }

  startEdit(callback) {
    if (this.state == "startEdit" || this.state == "editing" || !this.entity)
      return;
    this.state = "startEdit";
    // this._createPositionIndicator();
    if (!this.modifyHandler)
      this.modifyHandler = new Cesium.ScreenSpaceEventHandler(
        this.viewer.scene.canvas
      );
    let that = this;
    let editLabel;
    this.modifyHandler.setInputAction(function (evt) {
      let pick = that.viewer.scene.pick(evt.position);
      if (Cesium.defined(pick) && pick.id) {
        editLabel = pick.id;
        that.forbidDrawWorld(true);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
    this.modifyHandler.setInputAction(function (evt) {
      if (!editLabel) return;
      let cartesian = that.getCatesian3FromPX(evt.endPosition, that.viewer);
      if (!cartesian) return;
      if (that.entity) {
        that.entity.position.setValue(cartesian);
        that.position = cartesian;
        if (that.positionPoint) {
          that.positionPoint.position.setValue(cartesian);
        }
        that.state = "editing";
      }
      if (callback) callback();
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    this.modifyHandler.setInputAction(function (evt) {
      if (!editLabel) return;
      that.forbidDrawWorld(false);
      if (that.modifyHandler) {
        that.modifyHandler.destroy();
        that.modifyHandler = null;
        that.state = "editing";
      }
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  }
  endEdit(callback) {
    // 仅清理定位点
    if (this.positionPoint) {
      this.viewer.entities.remove(this.positionPoint);
      this.positionPoint = null;
    }

    if (this.modifyHandler) {
      this.modifyHandler.destroy();
      this.modifyHandler = null;
      if (callback) callback(this.entity);
    }
    this.forbidDrawWorld(false);
    this.state = "endEdit";
  }

  createLabel(cartesian) {
    if (!cartesian) return;
    // 使用this.style中的属性，而不是硬编码默认值
    let label = this.viewer.entities.add({
      position: cartesian,
      label: {
        text: this.style.text || "--",
        fillColor: this.style.fillColor
          ? Cesium.Color.fromCssColorString(this.style.fillColor).withAlpha(
            this.style.fillColorAlpha || 1
          )
          : Cesium.Color.WHITE,
        backgroundColor: this.style.backgroundColor
          ? Cesium.Color.fromCssColorString(
            this.style.backgroundColor
          ).withAlpha(this.style.backgroundColorAlpha || 1)
          : Cesium.Color.BLACK,
        style: Cesium.LabelStyle.FILL,
        outlineWidth: this.style.outlineWidth || 4,
        scale: this.style.scale || 1,
        pixelOffset: this.style.pixelOffset || Cesium.Cartesian2.ZERO,
        showBackground: this.style.showBackground !== undefined ? this.style.showBackground : true,
        heightReference: this.style.heightReference || 0,
        disableDepthTestDistance: Number.MAX_VALUE
      },
    });
    label.objId = this.objId;
    return label;
  }
  setPosition(cartesian) {
    if (!cartesian) return;
    this.position = cartesian.clone(); // 更新实例位置
    if (this.entity) {
      this.entity.position.setValue(this.position); // 同步实体位置
    }
    if (this.positionPoint) {
      this.positionPoint.position.setValue(this.position); // 同步定位点
    }
    console.log('位置已同步更新:', this.position);
  }
};

export default CreateLabel;
